﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.Composition;
using WaterRevenueMS.WebUI.Common;
using WaterRevenueMS.Core.Service.ReadMeterMS;
using WaterRevenueMS.Core.Service.BaseData;
using WaterRevenueMS.Core.Service.Customer;
using WaterRevenueMS.WebUI.Extension.Filters;
using WaterRevenueMS.Domain.ViewModels.ReadMeterMS.TaskTemplet;
using WaterRevenueMS.Domain.Common.Models;
using WaterRevenueMS.Componnent.Common;
using System.Linq.Expressions;
using WaterRevenueMS.Componnent.Entities.ReadMeterMS;
using WaterRevenueMS.WebUI.Extension.MvcHelper;
using WaterRevenueMS.Domain.ViewModels.BaseData.Area;
using WaterRevenueMS.Domain.ViewModels.BaseData.MeterBook;
using WaterRevenueMS.Domain.ViewModels.BaseData.MeterReader;
using WaterRevenueMS.Domain.ViewModels.Customer.MeterInfo;
using System.Data.OleDb;
using System.Data;

namespace WaterRevenueMS.WebUI.Controllers
{
    [Export]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class MeterTaskGenerateController : AdminController
    {
        [Import]
        private ITaskTempletService TaskTempletService { get; set; }
        [Import]
        private IAreaService AreaService { get; set; }
        [Import]
        private IMeterBookService MeterBookService { get; set; }
        [Import]
        private IMeterReaderService MeterReaderService { get; set; }
        [Import]
        private IMeterInfoService MeterInfoService { get; set; }



        [AdminLayout]
        public ActionResult Index()
        {
            var model = new TaskTempletModel();
            return View(model);
        }

        [AdminPermission(PermissionCustomMode.Ignore)]
        public ActionResult List(DataTableParameter param)
        {
            int total = TaskTempletService.TaskTemplets.Count(t => t.IsDeleted == false && t.IsTaskTemplet==false);

            var expr = BuildSearchCriteria();

            var filterResult = TaskTempletService.TaskTemplets.Where(expr).Select(t => new TaskTempletModel
            {
                Id = t.Id,
                Ren_WMC = t.Ren_WMC,
                Chao_BND = t.Chao_BND,
                Chao_BYD = t.Chao_BYD,
                AreaName = t.Area.Qu_YMC != null ? t.Area.Qu_YMC : "",
                MeterBookName = t.MeterBook.Biao_CMC != null ? t.MeterBook.Biao_CMC : "",
                MeterReaderName = t.MeterReader.Chao_BYMC != null ? t.MeterReader.Chao_BYMC : ""

            }).OrderBy(t => t.Id).Skip(param.iDisplayStart).Take(param.iDisplayLength).ToList();

            int sortId = param.iDisplayStart + 1;

            var result = from c in filterResult
                         select new[]
                        {
                            sortId++.ToString(), 
                            c.Ren_WMC,
                            c.Chao_BND.ToString(),
                            c.Chao_BYD.ToString(),
                            c.AreaName,
                            c.MeterBookName,
                            c.MeterReaderName,
                            c.Id.ToString()
                        };

            return Json(new
            {
                sEcho = param.sEcho,
                iDisplayStart = param.iDisplayStart,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = result
            }, JsonRequestBehavior.AllowGet);
        }


        public ActionResult Create()
        {
            var model = new TaskGenerateModel();
            InitTaskInfo(model);
            return PartialView(model);
        }

        [HttpPost]
        [AdminOperateLog]
        public ActionResult Create(TaskGenerateModel model)
        {
            if (ModelState.IsValid)
            {
                OperationResult result = TaskTempletService.Insert(model);
                if (result.ResultType == OperationResultType.Success)
                {
                    return Json(result);
                }
                else
                {
                    return PartialView(model);
                }
            }
            else
            {
                return PartialView(model);
            }
        }
    //  ID为任务ID
        [AdminPermission(PermissionCustomMode.Ignore)]
        public string SelectMeterToModel(int Id)
        {
            string fileName = System.Web.HttpContext.Current.Server.MapPath("~/") + "DownLoad";
            string outconnstring = string.Format("Provider = Microsoft.Jet.OLEDB.4.0 ;Data Source ={0};Extended Properties=\"dBASE III\";", fileName);
            OleDbConnection outConn = new OleDbConnection(outconnstring);
            
            try
            {

                outConn.Open();

                var tasks = MeterInfoService.MeterInfos.Where(t => t.RMeter_No == Id)
                   .Select(t => new MeterInfoModel
                   {
                       Id = t.Id,
                       RMeter_No = t.RMeter_No,
                       MeterBookNum = t.MeterBook.Biao_CBH,
                       CustomerNum = t.Customer.Yong_HBH,
                       CustomerName = t.Customer.Hu_ZXM,
                       CustomerAddress = t.Customer.Yong_HZZ,
                       MeterTypeName = t.MeterType.Yi_BLX,
                       Yi_BDZ = t.Yi_BDZ,
                       Yi_BDD = t.Yi_BDD,
                       ConcentratorTypeName = t.ConcentratorType.Ji_ZQLX,
                       Ji_ZQDZ = t.Ji_ZQDZ,
                       Ji_ZQTD = t.Ji_ZQTD,
                       An_ZWZ = t.An_ZWZ,
                       Bei_L = t.Bei_L,
                       //  Tong_XZT = t.MeterType.yi,
                       Fa_MZT = t.Fa_MZT,
                       Yi_BZT = t.Yi_BZT,
                       //  Chao_BCS= 0,
                       Chao_BDTBC = t.Chao_BDTBC,
                       Du_SBQ = t.Du_SBQ,
                       Du_SSQ = t.Du_SSQ,
                       Yong_LBC = t.Yong_LBC,
                       MeterBookName = t.MeterBook.Biao_CMC,
                       Chao_BYXM = t.MeterBook.Area.MeterMan.Chao_BYMC


                   });
                if (tasks.Count() > 0)
                {
                    MeterInfoModel model = tasks.First();
                    InsertIntoDBFBook(model, outConn);
                }
                foreach (var item in tasks)
                {
                    InsertIntoDBF(item, outConn);
                }
                return "操作成功";
                
            }
            catch (Exception c)
            {
                return "操作失败";
            }
            finally
            {
               
                if (outConn.State == System.Data.ConnectionState.Open)
                    outConn.Close();
                outConn.Dispose();
            }
            
          
        }
        private void InsertIntoDBF(MeterInfoModel model, OleDbConnection outConn)
        {
            
            OleDbCommand dc = outConn.CreateCommand();
            string StrSQL ="insert into mr(MRID,MRBFID,MRCID,CINAME,CIADR,MITYPE,MIADR,MICHAL,CCTYPE,CCADD,CCWAY,MICOL10,MIFIXVAL,MRREADOK,MIVALVE,MISTAT,MRRDNO,MRPDARDT,MRECODE,MRSCODE,MRVAL) "+
                            "VALUES({0},'{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}',{12},'{13}','{14}','{15}',{16},'{17}',{18},{19},{20})";
            try
            {
                dc.CommandType = CommandType.Text;
                string YBDZ = string.Format("{0:00000000000000}", model.Yi_BDZ);
                string JZQDZ = string.Format("{0:00000000000000}", model.Ji_ZQDZ);
                                                                                                                                          //model.ConcentratorTypeName
                dc.CommandText = string.Format(StrSQL, model.RMeter_No, model.MeterBookNum, model.CustomerNum, model.CustomerName, model.CustomerAddress, "0", YBDZ, "0","0" , JZQDZ, model.Ji_ZQTD.ToString(), model.An_ZWZ,"1", "0", "0", "0", 0, "0",0, model.Du_SBQ,0); ;
                dc.ExecuteNonQuery();
            }
            catch (Exception c)
            {
                
            }
            finally
            {
                dc.Dispose();
               
            }

        }
        private void InsertIntoDBFBook(MeterInfoModel model, OleDbConnection outConn)
        {

            OleDbCommand dc = outConn.CreateCommand();
            string StrSQL = "insert into BF(BFID,BRNAME,BFRPER) " +
                            "VALUES('{0}','{1}','{2}')";
            try
            {
                dc.CommandType = CommandType.Text;
                dc.CommandText = string.Format(StrSQL, model.MeterBookNum, model.MeterBookName, model.Chao_BYXM); ;
                dc.ExecuteNonQuery();
            }
            catch (Exception c)
            {

            }
            finally
            {
                dc.Dispose();

            }

        }
        //[HttpPost]
        //public ActionResult Edit(TaskTempletModel model)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        OperationResult result = TaskTempletService.Update(model);
        //        if (result.ResultType == OperationResultType.Success)
        //        {
        //            return Json(result);
        //        }
        //        else
        //        {
        //            return PartialView(model);
        //        }

        //    }
        //    else
        //    {
        //        return PartialView(model);
        //    }
        //}


        public ActionResult Delete(int Id)
        {
            OperationResult result = TaskTempletService.Delete(Id);
            return Json(result);
        }


        private Expression<Func<TaskTemplet, Boolean>> BuildSearchCriteria()
        {
            DynamicLambda<TaskTemplet> bulider = new DynamicLambda<TaskTemplet>();
            Expression<Func<TaskTemplet, Boolean>> expr = null;

            Expression<Func<TaskTemplet, Boolean>> tmpSolid = t => t.IsDeleted == false;

            expr = bulider.BuildQueryAnd(expr, tmpSolid);
            Expression<Func<TaskTemplet, Boolean>> tmpTemplet = t => t.IsTaskTemplet == false;
            expr = bulider.BuildQueryAnd(expr, tmpTemplet);
            return expr;
        }

        private void InitTaskInfo(TaskGenerateModel model)
        {
            //var areas = AreaService.Areas.Where(t => t.IsDeleted == false)
            //    .Select(t => new AreaModel
            //    {
            //        id = t.Id,
            //        Qu_YMC = t.Qu_YMC
            //    });
            //foreach (var item in areas)
            //{
            //    model.Areas.Add(new SelectListItem { Text = item.Qu_YMC, Value = item.id.ToString() });
            //}

            //var meterBooks = MeterBookService.MeterBooks.Where(t => t.IsDeleted == false)
            //    .Select(t => new MeterBookModel
            //    {
            //        id = t.Id,
            //        Biao_CMC = t.Biao_CMC
            //    });
            //foreach (var item in meterBooks)
            //{
            //    model.MeterBooks.Add(new SelectListItem { Text = item.Biao_CMC, Value = item.id.ToString() });
            //}
            //var meterReaders = MeterReaderService.MeterReaders.Where(t => t.IsDeleted == false)
            //    .Select(t => new MeterReaderModel
            //    {
            //        id = t.Id,
            //        Chao_BYMC = t.Chao_BYMC
            //    });
            //foreach (var item in meterReaders)
            //{
            //    model.MeterReaders.Add(new SelectListItem { Text = item.Chao_BYMC, Value = item.id.ToString() });
            //}
            var tasks = TaskTempletService.TaskTemplets.Where(t => t.IsDeleted == false && t.IsTaskTemplet == true)
                .Select(t => new TaskTempletModel { 
                    Id=t.Id,
                    Ren_WMC=t.Ren_WMC
                });
            foreach (var item in tasks)
            {
                model.TaskTemplets.Add(new SelectListItem {Text=item.Ren_WMC,Value=item.Id.ToString() });
            }
                
        }

    }
}
